﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;
using FadeJSON;
using Work.Weixin;
using Json2Excel;

namespace WorkWeiXin.Winforms
{
    public partial class Form1 : Form
    {
        private wxCorporation corporation;
        private wxOA appOA;

        public Form1()
        {
            InitializeComponent();
            string corpId = File.ReadAllLines("某某公司.corpid.tmp")[0];
            //this.str审批AgentId = File.ReadAllLines("某某公司.审批.AgentId.tmp")[0];
            string str审批Secret = File.ReadAllLines("某某公司.审批.Secret.tmp")[0];

            var oaAccessTokenCache = AccessTokenFileCache.Load("某某公司.审批.access_token");
            this.corporation = new wxCorporation(corpId);
            this.appOA = new wxOA(this.corporation, str审批Secret, oaAccessTokenCache);

        }

        private static readonly HttpClient client = new HttpClient();

        private void btnGetTemplateDetail_Click(object sender, EventArgs e)
        {
            this.btnGetTemplateDetail.Enabled = false;
            GetTemplateDetail();
            this.btnGetTemplateDetail.Enabled = true;
        }

        private void btnGetApprovalInfo_Click(object sender, EventArgs e)
        {
            this.btnGetApprovalInfo.Enabled = false;
            GetApprovalInfo();
            this.btnGetApprovalInfo.Enabled = true;
        }

        private void btnGetApprovalDetail_Click(object sender, EventArgs e)
        {
            this.btnGetApprovalDetail.Enabled = false;
            GetApprovalDetail();
            this.btnGetApprovalDetail.Enabled = true;
        }

        private void btnApplyEvent_Click(object sender, EventArgs e)
        {
            this.btnApplyEvent.Enabled = false;
            ApplyEvent();
            this.btnApplyEvent.Enabled = true;
        }

        private void GetTemplateDetail()
        {
            using (var sr = new StreamReader(@"GetTemplateDetail\template_id.txt"))
            {
                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var parts = line.Split(' ');
                    var name = parts[0];
                    var template_id = parts[1];
                    var detail = this.appOA.GetTemplateDetail(template_id);
                    File.WriteAllText(string.Format(
@"GetTemplateDetail\{0}({1}).json", name, template_id), detail);
                }
            }
        }

        private void GetApprovalInfo()
        {
            this.txtResult.Clear();

            DateTime endTime = DateTime.Now;
            DateTime startTime = endTime.Subtract(new TimeSpan(1, 0, 0, 0));
            bool next = true;
            int next_cursor = 0;
            while (next)
            {
                var result = this.appOA.GetApprovalInfo(startTime, endTime, next_cursor);
                var obj = Json.FromString(result);
                JsonBaseType jsonNext;
                if (obj.Value.TryGetValue("next_cursor", out jsonNext))
                {
                    next_cursor = (int)jsonNext.Value;
                }
                else
                {
                    next = false;
                }
                this.txtResult.AppendText(result);
                this.txtResult.AppendText(Environment.NewLine);
            }
        }
        private void GetApprovalDetail()
        {
            DateTime endTime = DateTime.Now;
            DateTime startTime = endTime.Subtract(new TimeSpan(1, 0, 0, 0));
            bool next = true;
            int next_cursor = 0;
            while (next)
            {
                var result = this.appOA.GetApprovalInfo(startTime, endTime, next_cursor);
                var obj = Json.FromString(result);
                IList<JsonBaseType> list = obj.Value["sp_no_list"].Value;
                foreach (var item in list)
                {
                    var sp_no = item.Value;
                    var detail = this.appOA.GetApprovalDetail(sp_no);
                    File.WriteAllText(string.Format(
    @"GetApprovalDetail\{0}.json", sp_no), detail);
                }

                JsonBaseType jsonNext;
                if (obj.Value.TryGetValue("next_cursor", out jsonNext))
                {
                    next_cursor = (int)jsonNext.Value;
                }
                else
                {
                    next = false;
                }

                this.txtResult.AppendText(result);
                this.txtResult.AppendText(Environment.NewLine);
            }
        }

        Random random = new Random();
        private void ApplyEvent()
        {
            var obj = new JsonObject();
            obj.Add("creator_userid", "YeWuYuanA");
            obj.Add("template_id", "C4NvsyND6zerE4brTG4eWifvhtxai5KjXg3FusAme");//测试单01
            obj.Add("use_template_approver", 1);//使用此模板在管理后台设置的审批流程，支持条件审批。
            //obj.Add("choose_department", 2);//提单者提单部门id，不填默认为主部门
            //// approver
            //{
            //    var list = new List<JsonObject>();
            //    {
            //        var item = new JsonObject();
            //        item.Add("attr", 2);//节点审批方式：1-或签；2-会签，仅在节点为多人审批时有效
            //        item.Add("userid", "ZongJingLiA");//审批节点审批人userid列表
            //        list.Add(item);
            //    }
            //    {
            //        var item = new JsonObject();
            //        item.Add("attr", 1);//节点审批方式：1-或签；2-会签，仅在节点为多人审批时有效
            //        item.Add("userid", "KuaiJiA");//审批节点审批人userid列表
            //        list.Add(item);
            //    }
            //    var approver = new JsonObject(list);
            //    obj.Add("approver", approver);
            //}
            //obj.Add("notifyer", "ChuNaA");
            //obj.Add("notify_type", 3);
            // apply_data
            int r = random.Next();
            {
                var list = new List<JsonBaseType>();
                {
                    var item = new JsonObject();
                    item.Add("control", "Text");
                    item.Add("id", "Text-1638417723135");
                    {
                        var value = new JsonObject();
                        value.Add("text", string.Format("测试单01-报销项目{0}", r));
                        item.Add("value", value);
                    }
                    list.Add(item);
                }
                //{
                //    var item = new JsonObject();
                //    item.Add("control", "Textarea");
                //    item.Add("id", "Textarea-1639035638068");
                //    {
                //        var value = new JsonObject();
                //        value.Add("text", string.Format("测试单01-备注{0}", r));
                //        item.Add("value", value);
                //    }
                //    list.Add(item);
                //}
                var contents = new JsonArray(list);
                var apply_data = new JsonObject();
                apply_data.Add("contents", contents);
                obj.Add("apply_data", apply_data);
            }
            // summary_list
            {
                var list = new List<JsonBaseType>();
                {
                    var noName = new JsonObject();
                    var item = new JsonObject();
                    item.Add("text", string.Format("测试单01-{0}-{1}", "YeWuYuanA", r));
                    item.Add("lang", "zh_CN");
                    var list2 = new JsonArray();
                    list2.Add(item);
                    noName.Add("summary_info", list2);
                    list.Add(noName);
                }
                {
                    var noName = new JsonObject();
                    var item = new JsonObject();
                    item.Add("text", string.Format("测试单01-备注{0}-{1}", "YeWuYuanA", r));
                    item.Add("lang", "zh_CN");
                    var list2 = new JsonArray();
                    list2.Add(item);
                    noName.Add("summary_info", list2);
                    list.Add(noName);
                }
                {
                    var noName = new JsonObject();
                    var item = new JsonObject();
                    item.Add("text", string.Format("测试单01-没了{0}-{1}", "YeWuYuanA", r));
                    item.Add("lang", "zh_CN");
                    var list2 = new JsonArray();
                    list2.Add(item);
                    noName.Add("summary_info", list2);
                    list.Add(noName);
                }
                var summary_list = new JsonArray(list);
                obj.Add("summary_list", summary_list);
            }
            string json = obj.ToString();
            this.txtResult.Text = this.appOA.ApplyEvent(json);
        }

        private void btnGetMedia_Click(object sender, EventArgs e)
        {
            this.btnGetMedia.Enabled = false;
            string media_id = @"WWCISP_EKA5mwb5Q-SEqHLgI-sk4muEw-YXBGUDG--Dgb5QBiJVQwixrrJQuNzm-NUVXDAhyS7hIJ2JTVStzZPrKRqV0mKeP6uvJDUWPHW7e-TczxPp0Dy6Du3sOqIcpyrO8aEV86Q086XyMy59_6wZ1HZIWrxh3IGaRHeGdQs0X7eXPVRAYwl1tbhrYpZui1XNKI4jMMHqyJYeFAZTTc4Efij0cF8FI0Yn5K7wOIuum6X4rK6Vzbua0jv0DSI1Uet6_Ry7cPRqMwThdsvud_3gGbsUyyNTM18ian2benJNfBUR7duVAfNGm5gkbCw1yAfAT-MVEFAZjTYY-9oC9vNp04Y6gE9haXel7Qqwcg3o0U1LT31HoHu4nG9zTTK3M7imA4M5-VnHjx3pilMilRSCUjIbagtXPOUYlXDuHm04MwR6KxKE3bggbA1CaGbmqnDZWFWVy-ffTQ3HmQjLWYBuVgz14kl8zAPA8H1N5fhCHRNXW9fYP3-dLgp8yspE-RsoEcLefrqsbdDIUfhclE7SmBk3RY_teM6-B8z_xHmJfIj-NdhYlKKqrzOQ1F0GFEdIMrWQ4okFeymcw8P1sMX9E1AhCxtQyPOfhoMMP3NFHd09CptKBJRiO_4UbfZSeeNhPysTkp_60HjDVK_oi05zmoG9vQ";
            string access_token = this.appOA.GetAccessToken();
            this.corporation.GetMedia(access_token, media_id);
            this.btnGetMedia.Enabled = true;
        }

        private void btnAllApprovals_Click(object sender, EventArgs e)
        {
            this.btnAllApprovals.Enabled = false;

            var fileTime = DateTime.Now;
            var endTime = DateTime.Now;
            while (endTime.Month >= 12)
            {
                DateTime startTime = endTime.Subtract(new TimeSpan(30, 0, 0, 0));
                bool next = true;
                int next_cursor = 0;
                while (next)
                {
                    var result = this.appOA.GetApprovalInfo(startTime, endTime, next_cursor);
                    var obj = Json.FromString(result);
                    var list = obj.Value["sp_no_list"].Value;
                    foreach (var item in list)
                    {
                        var sp_no = item.Value;
                        var detail = this.appOA.GetApprovalDetail(sp_no);

                        File.WriteAllText(string.Format(
        @"GetApprovalDetail\{0}.json", sp_no), detail);
                    }

                    JsonBaseType jsonNext;
                    if (obj.Value.TryGetValue("next_cursor", out jsonNext))
                    {
                        next_cursor = (int)jsonNext.Value;
                    }
                    else
                    {
                        next = false;
                    }

                    this.txtResult.AppendText(result);
                    this.txtResult.AppendText(Environment.NewLine);
                }
                endTime = startTime;
            }

            this.btnAllApprovals.Enabled = true;

        }

        private void btnJson2Excel_Click(object sender, EventArgs e)
        {
            this.btnJson2Excel.Enabled = false;
            var csvDict = new Dictionary<string, CSVFile>();
            foreach (var jsonFilename in Directory.GetFiles(@"GetApprovalDetail", "*.json"))
            {
                var content = File.ReadAllText(jsonFilename);
                var jsonObject = Json.FromString(content);
                var templateId = GetTemplateId(jsonObject.Value["info"]);
                var csvFile = GetFile(csvDict, templateId);
                if (csvFile.Columns.Count == 0)
                {
                    WriteTitles(csvFile, jsonObject.Value["info"]["apply_data"]["contents"]);
                }

                WriteData(csvFile, jsonObject.Value["info"]["apply_data"]["contents"]);
            }
            this.btnJson2Excel.Enabled = true;

        }

        private void WriteData(CSVFile csvFile, JsonBaseType jsonObject)
        {
            IList<JsonBaseType> array = jsonObject.Value;
            var row = new string[array.Count];
            for (int i = 0; i < array.Count; i++)
            {
                string cell = GetCell(array[i]);
                row[i] = cell;
            }

            csvFile.AddRow(row);
        }

        private string GetCell(JsonBaseType jsonObject)
        {
            var result = "Error";

            var type = (eControlType)Enum.Parse(typeof(eControlType), jsonObject.Value["control"].Value);
            switch (type)
            {
                case eControlType.Unknown:
                    break;
                case eControlType.Text:
                    break;
                case eControlType.Textarea:
                    break;
                case eControlType.Number:
                    break;
                case eControlType.Money:
                    break;
                case eControlType.Formula:
                    break;
                case eControlType.Date_day:
                    break;
                case eControlType.Date_hour:
                    break;
                case eControlType.DateRange_halfday:
                    break;
                case eControlType.Selector_single:
                    break;
                case eControlType.Selector_multi:
                    break;
                case eControlType.Contact_user:
                    break;
                case eControlType.Contact_department:
                    break;
                case eControlType.Location:
                    break;
                case eControlType.File:
                    break;
                case eControlType.RelatedApproval:
                    break;
                case eControlType.Table:
                    break;
                case eControlType.Tips:
                    break;
                default:
                    throw new NotImplementedException();
                    break;
            }

            throw new NotImplementedException();
        }

        private void WriteTitles(CSVFile csvFile, JsonBaseType jsonObject)
        {
            IList<JsonBaseType> array = jsonObject.Value;
            foreach (var item in array)
            {
                string key = item.Value["id"].Value;
                string title = item.Value["title"][0]["text"].Value;
                var column = new CSVColumn(key);
                csvFile.Columns.Add(column);
            }
        }

        private CSVFile GetFile(Dictionary<string, CSVFile> csvDict, string templateId)
        {
            CSVFile result;
            if (!csvDict.TryGetValue(templateId, out result))
            {
                result = new CSVFile();
                csvDict.Add(templateId, result);
            }

            return result;
        }

        private string GetTemplateId(JsonBaseType jsonObject)
        {
            var sp_name = jsonObject.Value["sp_name"].Value;
            var template_id = jsonObject.Value["template_id"].Value;
            return string.Format("{0}({1})", sp_name, template_id);
        }

    }
}
